import { resolve } from 'node:path'
import vue from '@vitejs/plugin-vue'
import { EleAdminResolver } from 'ele-admin-plus/es/utils/resolvers'
import Unocss from 'unocss/vite'
import AutoImport from 'unplugin-auto-import/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import Components from 'unplugin-vue-components/vite'
import { transformLazyShow } from 'v-lazy-show'
import { defineConfig } from 'vite'
import Compression from 'vite-plugin-compression'

export default defineConfig(({ command }) => {
  const isBuild = command === 'build'
  const alias = {
    '@/': `${resolve('src')}/`,
    'vue-i18n': 'vue-i18n/dist/vue-i18n.cjs.js',
  }
  const plugins = [
    vue({
      template: {
        compilerOptions: {
          nodeTransforms: [
            transformLazyShow,
          ],
        },
      },
    }),
    Unocss(),
    AutoImport({
      imports: [
        'vue',
        'vue-router',
        'pinia',
        'vue-i18n',
        {
          '@/utils': [['*', 'utils']],
        },
      ],
      // 配置声明文件路径
      // dts: false, // './auto-import.d.ts'
      dts: './auto-import.d.ts',
    }),
  ]
  if (isBuild) {
    // 组件按需引入
    plugins.push(

      Components({
        dts: false,
        resolvers: [
          ElementPlusResolver({
            importStyle: 'sass',
          }),
          EleAdminResolver({
            importStyle: 'sass',
          }),
        ],
      }),
    )
    // gzip压缩
    // plugins.push(
    //   Compression({
    //     disable: !isBuild,
    //     threshold: 10240,
    //     algorithm: 'gzip',
    //     ext: '.gz',
    //   }),
    // )
  }
  else {
    // 开发环境全局安装
    alias['./as-needed'] = './global-import'
  }
  return {
    resolve: { alias },
    plugins,
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "@/styles/variables.scss" as *;`,
        },
      },
    },
    optimizeDeps: {
      include: [
        'echarts/core',
        'echarts/charts',
        'echarts/renderers',
        'echarts/components',
        'vue-echarts',
        'echarts-wordcloud',
        'sortablejs',
        'vuedraggable',
      ],
    },
    build: {
      target: 'chrome63',
      chunkSizeWarningLimit: 2000,
      rollupOptions: {
        // 排除示例目录
        external: [
          /\/src\/views\/example\/.*/,
          /\/src\/views\/extension\/.*/,
          /\/src\/views\/form\/.*/,
          /\/src\/views\/list\/.*/,
        ],
      },
    },
    server: {
      port: 66, // 自定义端口
      // 是否开启 https
      https: false,
    },
  }
})
